package com.example.demo.service.impl;

import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.exception.LoginException;
import com.example.demo.exception.UserNotFoundException;
import com.example.demo.exception.WrongPasswordException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.request.CreateUserRequest;
import com.example.demo.request.UpdateUserRequest;
import com.example.demo.request.LoginRequest;
import com.example.demo.response.LoginResponse;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.IOException;
import com.example.demo.util.ExcelUtil;
import com.example.demo.exception.BusinessException;
import java.util.Date;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserDTO> getUsers(int page, int size) {
        int offset = page * size;
        List<User> users = userMapper.selectWithPagination(offset, size);
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public long countUsers() {
        return userMapper.count();
    }

    @Override
    public UserDTO getUserById(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return convertToDTO(user);
    }

    @Override
    @Transactional
    public User createUser(CreateUserRequest request) {
        
        // 检查统一认证号是否已存在
        User existingUser = userMapper.selectByAuthId(request.getAuthId());
        if (existingUser != null) {
            throw new BusinessException("统一认证号已存在");
        }
        
        // 检查邮箱是否已存在
        if (request.getEmail() != null && !request.getEmail().isEmpty()) {
            User existingByEmail = userMapper.selectByEmail(request.getEmail());
            if (existingByEmail != null) {
                throw new BusinessException("邮箱已存在");
            }
        }
        
        User user = new User();
        user.setAuthId(request.getAuthId());
        user.setUserName(request.getUserName());
        user.setEmail(request.getEmail());
        user.setDeptId(request.getDeptId());
        user.setDeptName(request.getDeptName());
        user.setUserType(request.getUserType());
        user.setPassword(request.getPassword()); // 实际开发中应该加密密码
        
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            throw new BusinessException("用户创建失败");
        }
        
        return user;
    }

    @Override
    @Transactional
    public void updateUser(Integer id, UpdateUserRequest request) {
        
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查统一认证号是否被其他用户使用
        if (!user.getAuthId().equals(request.getAuthId())) {
            User existingUser = userMapper.selectByAuthId(request.getAuthId());
            if (existingUser != null) {
                throw new BusinessException("统一认证号已存在");
            }
        }
        
        // 检查邮箱是否被其他用户使用
        if (request.getEmail() != null && !request.getEmail().isEmpty() && 
            !request.getEmail().equals(user.getEmail())) {
            User existingByEmail = userMapper.selectByEmail(request.getEmail());
            if (existingByEmail != null) {
                throw new BusinessException("邮箱已存在");
            }
        }
        
        user.setAuthId(request.getAuthId());
        user.setUserName(request.getUserName());
        user.setEmail(request.getEmail());
        user.setDeptId(request.getDeptId());
        user.setDeptName(request.getDeptName());
        user.setUserType(request.getUserType());
        // 密码修改已移除，请使用专门的修改密码接口
        
        try {
            userMapper.updateById(user);
        } catch (Exception e) {
            throw new BusinessException("用户更新失败");
        }
    }

    @Override
    @Transactional
    public void deleteUser(Integer id) {
        
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        try {
            userMapper.deleteById(id);
        } catch (Exception e) {
            throw new BusinessException("用户删除失败");
        }
    }
    
    @Override
    public List<UserDTO> searchUsersByName(String name) {
        List<User> users = userMapper.selectByNameLike(name);
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Map<String, Object> batchImportUsers(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        List<String> errors = new ArrayList<>();
        List<User> validUsers = new ArrayList<>();

        try {
            List<User> users = ExcelUtil.parseExcelFile(file);
            
            // 预先验证所有用户数据
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                String authId = user.getAuthId();
                boolean hasError = false;

                // 校验 authId 是否已存在
                User existingByAuthId = userMapper.selectByAuthId(authId);
                if (existingByAuthId != null) {
                    errors.add("第" + (i + 2) + "行: 统一认证号已存在: " + authId);
                    hasError = true;
                }

                // 校验邮箱是否重复
                if (user.getEmail() != null && !user.getEmail().isEmpty()) {
                    User existingByEmail = userMapper.selectByEmail(user.getEmail());
                    if (existingByEmail != null) {
                        errors.add("第" + (i + 2) + "行: 邮箱已存在: " + user.getEmail());
                        hasError = true;
                    }
                }

                // 基本数据验证
                if (user.getAuthId() == null || user.getAuthId().trim().isEmpty()) {
                    errors.add("第" + (i + 2) + "行: 统一认证号不能为空");
                    hasError = true;
                }
                if (user.getUserName() == null || user.getUserName().trim().isEmpty()) {
                    errors.add("第" + (i + 2) + "行: 用户名不能为空");
                    hasError = true;
                }

                if (!hasError) {
                    validUsers.add(user);
                }
            }

            // 批量插入有效用户
            if (!validUsers.isEmpty()) {
                userMapper.batchInsert(validUsers);
            } else {
            }

            result.put("success", true);
            result.put("message", "导入完成");
            result.put("successCount", validUsers.size());
            result.put("totalCount", users.size());
            result.put("errorCount", errors.size());
            result.put("errors", errors);


        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            throw new RuntimeException("批量导入失败", e);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "数据处理错误: " + e.getMessage());
            throw new RuntimeException("批量导入失败", e);
        }

        return result;
    }

    @Override
    public byte[] batchExportUsers() {
        try {
            // 获取所有用户数据
            List<User> users = userMapper.selectAll();
            
            // 生成Excel文件
            byte[] excelData = ExcelUtil.exportUsersToExcel(users);
            
            return excelData;
        } catch (Exception e) {
            throw new BusinessException("导出用户数据失败: " + e.getMessage());
        }
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        // 根据统一认证号查询用户
        User user = getUserByAuthId(request.getAuthId());
        if (user == null) {
            throw new UserNotFoundException("用户不存在");
        }

        // 验证密码（实际应该使用加密密码）
        if (!user.getPassword().equals(request.getPassword())) {
            throw new WrongPasswordException("密码错误");
        }

        // 生成token（简化版，实际应该使用JWT等）
        String token = UUID.randomUUID().toString();
        // 模拟token过期时间，实际应该设置合理的过期时间
        Date expireDate = new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000);
        String expireTime = expireDate.toString();

        // 构造返回结果
        LoginResponse response = new LoginResponse();

        // 根据用户类型设置重定向路径和权限
        String userType = user.getUserType();
        if ("管理员".equals(userType)) {
            response.setRedirectPath("/admin");
            response.setHasPermission(true);
            response.setUserInfo(convertToDTO(user));
            response.setToken(token);
            response.setExpireTime(expireTime);
        } else if ("开发".equals(userType) || "测试".equals(userType) || "运维".equals(userType) || "架构".equals(userType)) {
            response.setRedirectPath("/user");
            response.setHasPermission(true);
            response.setUserInfo(convertToDTO(user));
            response.setToken(token);
            response.setExpireTime(expireTime);
        } else if ("用户".equals(userType) || "其他".equals(userType)) {
            // 普通用户可以登录，跳转到用户界面
            response.setRedirectPath("/user");
            response.setHasPermission(true);
            response.setUserInfo(convertToDTO(user));
            response.setToken(token);
            response.setExpireTime(expireTime);
        } else {
            // 未定义的用户类型默认允许登录，但跳转到基本用户界面
            response.setRedirectPath("/user");
            response.setHasPermission(true);
            response.setUserInfo(convertToDTO(user));
            response.setToken(token);
            response.setExpireTime(expireTime);
        }

        return response;
    }

    @Override
    public User getUserByAuthId(String authId) {
        return userMapper.selectByAuthId(authId);
    }
    
    @Override
    @Transactional
    public void changePassword(Integer userId, String oldPassword, String newPassword) {
        
        // 查询用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证旧密码是否正确
        if (!user.getPassword().equals(oldPassword)) {
            throw new BusinessException("旧密码不正确");
        }
        
        // 更新密码
        user.setPassword(newPassword);
        
        try {
            userMapper.updateById(user);
        } catch (Exception e) {
            throw new BusinessException("密码修改失败");
        }
    }
    
    @Override
    public List<UserDTO> getUsersByDeptId(Integer deptId) {
        
        if (deptId == null) {
            throw new BusinessException("部门ID不能为空");
        }
        
        try {
            List<User> users = userMapper.selectByDeptId(deptId);
            
            return users.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            throw new BusinessException("查询用户失败");
        }
    }

    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setUserId(user.getUserId());
        dto.setAuthId(user.getAuthId());
        dto.setUserName(user.getUserName());
        dto.setEmail(user.getEmail());
        dto.setDeptId(user.getDeptId());
        dto.setDeptName(user.getDeptName());
        dto.setUserType(user.getUserType());
        return dto;
    }
}